﻿Imports SchemaMikeConnellMinistries
Imports SchemaMembership
'Imports Microsoft.Office.Interop
Imports Framework
Imports System.Security.Cryptography
Imports System.Text.ASCIIEncoding

Module Module1

    'Dim office As New Word.Application





    Sub Main()

        Dim sb As New Text.StringBuilder
        For Each i As CProductList.CTagFreq In CProduct.Cache.Active.Sermons.MikeConnell.Tags
            If i.Freq <= 1 Then Continue For
            sb.Append(i.Tag).Append(";").AppendLine(i.Freq)
        Next
        IO.File.WriteAllText("d:\mikeconnell.txt", sb.ToString)

        sb.Clear()
        For Each i As CProductList.CTagFreq In CProduct.Cache.Active.Sermons.Chinese.AltTags
            If i.Freq <= 1 Then Continue For
            sb.Append(i.Tag).Append(";").AppendLine(i.Freq)
        Next
        IO.File.WriteAllText("d:\chinese.txt", sb.ToString)

        sb.Clear()
        For Each i As CProductList.CTagFreq In CProduct.Cache.Active.Sermons.GetBySpeaker1or2Id(ESpeaker.ShaneWillard).Tags
            If i.Freq <= 1 Then Continue For
            sb.Append(i.Tag).Append(";").AppendLine(i.Freq)
        Next
        IO.File.WriteAllText("d:\shanewillard.txt", sb.ToString)


        'RefreshFromRss("http://invercargillchristiancentre.podbean.com/feed/", "D:\audio\shane_willard\invercargill\", "Shane Willard")
        RefreshFromRss("http://www.shanewillardministries.org/main/rss/SWMTeaching.xml", "D:\audio\shane_willard\")
        Console.ReadLine()
        Exit Sub



        'Dim nv As New CNameValueList(1)
        'nv.Add(New CNameValue("FileName", String.Empty))

        'For Each i As CFile In CFile.Cache.GetByExtensionId(EExtension.Mp3).SortBy("FileId")
        '    Console.WriteLine(i.FileName)

        '    Dim p As CProduct = i.Product
        '    Dim sb As New Text.StringBuilder(p.ProductName.Trim.Replace("/", ","))
        '    'sb.Replace(" ", "-")
        '    sb.Replace("?", String.Empty)
        '    sb.Replace(":", " -")
        '    sb.Replace("&", "and")

        '    sb.Append("_").Append(p.SpeakerName.Trim) '.Replace(" ", ""))
        '    sb.Append("_").Append(p.ProductCreated.ToString("dd-MM-yyyy"))
        '    If i.Product.Am.HasValue Then
        '        sb.Append("_").Append(IIf(p.Am.Value, "am", "pm"))
        '    End If

        '    sb.Append(IO.Path.GetExtension(i.FileName))

        '    sb.Insert(0, IO.Path.GetDirectoryName(i.FileName) & "/")
        '    sb.Replace("\", "/")
        '    If sb(0) <> "/" Then sb.Insert(0, "/")

        '    Console.WriteLine(sb.ToString)

        '    If i.FileName.ToLower.Equals(sb.ToString.ToLower) Then
        '        Console.WriteLine("*Done")
        '        Continue For
        '    End If

        '    Dim p1 As String = CConfig.DropboxPublic & i.FileName
        '    Dim p2 As String = CConfig.DropboxPublic & sb.ToString

        '    If IO.File.Exists(p1) AndAlso Not IO.File.Exists(p2) Then
        '        Try
        '            IO.File.Move(p1, p2)
        '        Catch ex As Exception
        '            Console.WriteLine(ex.Message)
        '        End Try

        '        nv(0).Value = sb.ToString
        '        CDataSrc.Default.Update(nv, New CWhere(CFile.TABLE_NAME, New CCriteria("FileId", i.FileId), Nothing))
        '    Else
        '        Console.WriteLine("Error: File already exists")
        '    End If

        '    Threading.Thread.Sleep(5000)

        'Next
        'Exit Sub



        For Each i As CFile In CFile.Cache
            Dim index As Integer = i.FileName.ToLower.IndexOf("litchwark")
            If index < 0 Then Continue For
            Dim oldName As String = i.FileName
            Dim newName As String = i.FileName.Substring(0, index) & "Li" & i.FileName.Substring(index + 9).Replace("doug", "Doug").Replace("kalinda", "Kalinda")

            Dim oldPath As String = CConfig.DropboxPublic & oldName
            Dim newPath As String = CConfig.DropboxPublic & newName
            IO.File.Move(oldPath, newPath)
            i.FileName = newName
            i.SaveWithoutAudit()
        Next
        Exit Sub


        RecurseFolder_DeleteEmptyDirs(CConfig.DropboxPublic)


        Dim pub As List(Of String) = RecurseFolder_ListAllFiles(CConfig.DropboxPublic)
        Dim arc As List(Of String) = RecurseFolder_ListAllFiles(CConfig.DropboxArchive)
        For Each i As String In pub
            For Each j As String In arc
                If i.ToLower = j.ToLower Then
                    IO.File.Delete(CConfig.DropboxPublic & i)
                End If
            Next
        Next



        Dim inUse As List(Of String) = CFile.Cache.NamesNormalised


        Dim htms As List(Of String) = RecurseFolder_ListHtmFiles(CConfig.DropboxPublic)
        Dim done As New List(Of String)(htms.Count)
        For Each i As String In htms
            If done.Contains(i) Then Continue For
            done.Add(i)

            Dim matching As New List(Of String)(2)
            For Each j As String In htms
                If i = j Then Continue For
                If IO.Path.GetFileName(i).ToLower = IO.Path.GetFileName(j).ToLower Then matching.Add(j)
            Next
            If matching.Count = 0 Then Continue For
            done.AddRange(matching)

            Console.WriteLine("File: " & i)
            Console.WriteLine("Matching:")
            Console.WriteLine(String.Concat(0, ". ", IIf(inUse.Contains(i.ToLower), "* ", "  "), IO.Path.GetDirectoryName(i), vbTab, CUtilities.FileSize(CConfig.DropboxPublic & i)))
            For Each j As String In matching
                Console.WriteLine(String.Concat(1 + matching.IndexOf(j), ". ", IIf(inUse.Contains(j.ToLower), "* ", "  "), IO.Path.GetDirectoryName(j), vbTab, CUtilities.FileSize(CConfig.DropboxPublic & j)))
            Next

            Dim notInUse As New List(Of String)(matching.Count + 1)
            If Not inUse.Contains(i.ToLower) Then notInUse.Add(i)
            For Each j As String In matching
                If Not inUse.Contains(j.ToLower) Then notInUse.Add(j)
            Next
            If 0 = notInUse.Count Then
                Console.WriteLine("All files in use")
            ElseIf notInUse.Count > matching.Count Then
                Console.WriteLine("No files in use")
            Else
                Console.WriteLine("Delete " & CUtilities.CountSummary(notInUse, "file") & " not in use? (y/n)")
                If "y" = Console.ReadLine() Then
                    For Each j As String In notInUse
                        Dim archive As String = CConfig.DropboxArchive & j
                        Dim dir As String = IO.Path.GetDirectoryName(archive)
                        If Not IO.Directory.Exists(dir) Then IO.Directory.CreateDirectory(dir)
                        IO.File.Move(CConfig.DropboxPublic & j, archive)
                        Console.WriteLine("DELETED: " & j)
                    Next
                End If
            End If
            Console.WriteLine()
        Next
        Exit Sub

        Dim folderPath As String = "D:\Dropbox_MikeConnellMinistries\Dropbox\Public\"

        For Each i As CFile In CFile.Cache.Mp3s
            If i.FileName.ToLower.EndsWith("am.mp3") OrElse (i.FileName.ToLower.Contains("am") AndAlso Not i.FileName.ToLower.Contains("pm")) Then
                With i.Product
                    If .ProductCreated.Hour = 0 Then
                        .ProductCreated = .ProductCreated.AddHours(1)
                        .Save()
                    ElseIf .ProductCreated.Hour = 12 Then
                        .ProductCreated = .ProductCreated.AddHours(-11)
                        .Save()
                    End If
                End With
            ElseIf i.FileName.ToLower.EndsWith("pm.mp3") OrElse (i.FileName.ToLower.Contains("pm") AndAlso Not i.FileName.ToLower.Contains("am")) Then
                With i.Product
                    If .ProductCreated.Hour = 0 Then
                        .ProductCreated = .ProductCreated.AddHours(12)
                        .Save()
                    ElseIf .ProductCreated.Hour = 1 Then
                        .ProductCreated = .ProductCreated.AddHours(11)
                        .Save()
                    End If
                End With
            Else
                With i.Product

                End With
            End If
        Next
        Exit Sub


        RecurseFolder_ConvertDoc2Htm("D:\Dropbox_MikeConnellMinistries\Dropbox\Public\word\2000_ToRunAndNotGrowTired\")
        Exit Sub



        For Each i As CFile In CFile.Cache
            Dim filePath As String = String.Concat(folderPath, i.FileName)
            If Not IO.File.Exists(filePath) Then
                Console.WriteLine("MISSING: " & i.FileName)
                Continue For
            End If

            If i.FileSize > 0 Then Continue For
            i.FileSize = New IO.FileInfo(filePath).Length
            i.Save()
        Next
        'office.Quit()

        Exit Sub




        'Dim path As String = "D:\Dropbox_MikeConnellMinistries\Dropbox\Public\word\BusinessmensCell\"
        'For Each i As String In IO.Directory.GetFiles(path & "2005\")
        '    Dim htm As Word.Document = office.Documents.Open(i)
        '    htm.SaveAs(i.Substring(0, i.Length - 4) & ".doc", Word.WdSaveFormat.wdFormatDocument)
        '    htm.Close()

        'Next
        'office.Quit()

        Exit Sub


        Dim files As List(Of String) = RecurseFolder_ListHtmFiles(folderPath)
        Dim docs As List(Of String) = RecurseFolder_ListDocFiles(folderPath)
        For Each i As String In files
            '1. Find .htm files in html that are NOT in files table
            If Not Contains(CFile.Cache, i) Then
                Console.WriteLine(i & " - looking to import")
                '2. Look for matching word document, guess the date
                Dim doc As String = Nothing
                For Each d As String In docs
                    If IO.Path.GetFileNameWithoutExtension(d) = IO.Path.GetFileNameWithoutExtension(i) Then
                        doc = d
                        Exit For
                    End If
                Next
                If IsNothing(doc) Then
                    Console.WriteLine("No doc found to guess date")
                    'todo: look at file name instead for date info
                    Continue For
                End If
                Dim created As DateTime = IO.File.GetLastWriteTime(folderPath & doc)
                Console.WriteLine("Guess date: " & created.ToString("yyyy MMM dd"))


                '3. Use the com object to read the title
                Dim title As String = IO.Path.GetFileNameWithoutExtension(doc)
                Dim filePath As String = String.Concat(folderPath, doc)
                'Dim word As Word.Document = office.Documents.Open(filePath)
                'If word.Sentences.Count > 0 Then title = word.Sentences(0).Text
                Console.WriteLine("Guess title: " & title)

                'Check for anything on that date
                Dim same As CProduct = Nothing
                Dim list As New CProductList(2)
                For Each p As CProduct In CProduct.Cache.Sermons
                    If p.ProductCreated.Date = created Then
                        list.Add(p)
                        If title.ToLower.Replace(" ", "") = p.ProductName.ToLower.Replace(" ", "") Then same = p
                    End If
                Next

                If list.Count > 0 AndAlso IsNothing(same) Then
                    For Each p As CProduct In list
                        Console.WriteLine("#" & (1 + list.IndexOf(p)) & ": " & p.ProductName & "?")
                    Next
                    Dim choose As Integer = Integer.Parse(Console.ReadLine())
                    If choose > 0 Then same = list(choose - 1)
                End If

                If IsNothing(same) Then
                    same = New CProduct()
                    same.ProductCreated = created
                    same.ProductName = title
                    same.ProductTypeId_ = EProductType.Sermon
                    same.ProductDescription = ""
                    same.ProductIsActive = True
                    same.ProductLanguageId = ELanguage.English
                    same.SaveWithoutAudit()
                    'create 
                End If
                'add file
                Dim file As New CFile()
                file.FileProductId = same.ProductId
                file.FileName = i
                file.FileSize = New IO.FileInfo(String.Concat(folderPath, i)).Length
                file.Save()
            End If
        Next
        Exit Sub




        ''insert html at the top of all the notes, linking back
        'Dim ws As New Framework.CWebSrcBinary("http://mikeconnellministries.com", "")


        'For Each i As CFile In New CFile.SelectAll
        '    Dim filePath As String = String.Concat(folderPath, i.FileName)
        '    If Not IO.File.Exists(filePath) Then
        '        Console.WriteLine(i.FileName)

        '        For Each j As String In files
        '            If IO.Path.GetFileName(j) = IO.Path.GetFileName(i.FileName) Then
        '                Console.WriteLine(j & " (new path)")
        '                i.FileName = j
        '                i.Save()
        '                Exit For
        '            End If
        '        Next
        '    End If
        'Next
        'Exit Sub




        Dim localPath As String = "D:\Dropbox_MikeConnellMinistries\Dropbox\Public\" ' "D:\My Sunday Messages\" '"c:\dropbox\html\"
        For Each i As CProduct In CProduct.Cache
            If Not i.Files.HasHtm Then Continue For

            Dim file As CFile = i.Files.FirstHtm
            Dim filePath As String = String.Concat(localPath, file.FileName)
            If Not IO.File.Exists(filePath) Then
                Console.WriteLine("File not found: " & filePath)
                Console.ReadLine()
                Continue For
            End If

            'Dim doc As Word.Document = office.Documents.Open(filePath)
            'Try
            '    If doc.Hyperlinks.Count = 0 Then
            '        Dim lnk As Word.Hyperlink = doc.Hyperlinks.Add(doc.Sentences(1), LinkUrl(i), Nothing, i.ProductNameAndContents, Nothing, "_top")
            '        doc.SaveAs(filePath, Word.WdSaveFormat.wdFormatFilteredHTML)
            '    End If
            'Catch
            '    Throw
            'Finally
            '    doc.Close()
            'End Try


            'Dim html As String = IO.File.ReadAllText(filePath)
            'Dim lower As String = html.ToLower
            'If lower.Contains("mikeconnellministries.com") Then
            '    Console.WriteLine("Skipped: " & filePath)
            '    Continue For
            'End If

            'Dim bodyStart As Integer = lower.IndexOf("<body")
            'If -1 = bodyStart Then
            '    Console.WriteLine("Body tag not found: " & filePath)
            '    Console.ReadLine()
            '    Continue For
            'End If
            'Dim bodyEnd As Integer = lower.IndexOf(">", bodyStart) + 1
            'Dim lhs As String = html.Substring(0, bodyEnd)
            'Dim rhs As String = html.Substring(bodyEnd)

            'template.Reset()
            'template.Replace("productId", i.ProductId)
            'template.Replace("productName", i.ProductName)
            'template.Replace("productNameEncoded", Web.HttpUtility.UrlEncode(i.ProductName))
            'html = String.Concat(lhs, template.Template, rhs)
            'IO.File.WriteAllText(filePath, html, Text.Encoding.UTF8)

            'Console.WriteLine("Done: " & filePath)
        Next

        Console.ReadLine()
        Exit Sub





        'Conversion from doc to html
        'Dim localPath As String = "d:\My sunday messages\"
        'RecurseFolder_ConvertDoc2Htm(localPath)


        'Bulk Import of Notes
        'Dim files As List(Of String) = RecurseFolder_ListHtmFiles(localPath)


        'Dim failed As New List(Of String)

        'CProduct.Cache = New CProduct.SelectAll
        'CProductType.Cache = New CProductType.SelectAll
        'CFile.Cache = New CFile.SelectAll

        'Dim o As Object = CProduct.Cache(0).Files
        'For Each i As String In files
        '    Console.WriteLine("Checking: " & i)

        '    Dim name As String = IO.Path.GetFileNameWithoutExtension(i)
        '    Dim shortName As String = name
        '    Dim lastSpace As Integer = name.LastIndexOf(" ")

        '    Dim ddmmyy As String() = Nothing
        '    If lastSpace = -1 Then
        '        ddmmyy = name.Split("-")
        '    Else
        '        Dim last678 As String = name.Substring(lastSpace, name.Length - lastSpace).Trim
        '        ddmmyy = last678.Split("-")
        '        shortName = name.Substring(0, lastSpace).Trim
        '    End If


        '    If ddmmyy.Length <> 3 Then
        '        Dim firstSpace As Integer = name.IndexOf(" ")
        '        Dim first678 As String = name.Substring(firstSpace)
        '        ddmmyy = first678.Split("-")
        '        shortName = name.Substring(firstSpace + 1).Trim
        '    End If


        '    If ddmmyy.Length <> 3 Then
        '        failed.Add(i)
        '        Console.WriteLine("Couldnt read date: " & i)
        '        Continue For
        '    End If

        '    Try

        '        Dim d As New DateTime(2000 + Integer.Parse(ddmmyy(2)), Integer.Parse(ddmmyy(1)), Integer.Parse(ddmmyy(0)))
        '        If d.Year > 3000 Then d = d.AddYears(-2000)
        '        Dim matching As New CProductList
        '        For Each j As CProduct In CProduct.Cache.Sermons
        '            If j.ProductCreated.Date.Equals(d) Then matching.Add(j)
        '        Next


        '        Dim p As New CProduct
        '        p.ProductCreated = d
        '        p.ProductName = shortName
        '        p.ProductTypeId_ = EProductType.Sermon
        '        p.ProductDescription = "Notes only"
        '        p.ProductIsActive = True
        '        p.ProductIsFree = True
        '        p.ProductLanguageId = ELanguage.English

        '        If matching.Count > 0 Then
        '            Dim selection As Integer = Integer.MinValue
        '            While selection < 0 OrElse selection > matching.Count
        '                Console.WriteLine("Found several matches for: " & p.ProductCreated.ToLongDateString)
        '                Console.WriteLine(String.Concat("#0: ", p.ProductName, " (create new)"))
        '                For Each j As CProduct In matching
        '                    Console.WriteLine(String.Concat("#", 1 + matching.IndexOf(j), ": ", j.ProductName))
        '                Next
        '                Dim s As String = Console.ReadLine().Trim
        '                Integer.TryParse(s, selection)
        '            End While

        '            If selection = 0 Then
        '                p.SaveWithoutAudit()
        '            ElseIf selection <= matching.Count Then
        '                p = matching(selection - 1)
        '                If p.ProductName = "Mike Connell" Then
        '                    p.ProductName = shortName
        '                    p.Save()
        '                End If
        '            End If
        '        Else
        '            p.SaveWithoutAudit()
        '        End If

        '        If p.Files.Count > 1 Then
        '            Console.WriteLine("Skipped: " & i & " (already has >1 files)")
        '            Continue For
        '        End If

        '        Dim file As New CFile
        '        file.FileProductId = p.ProductId
        '        file.FileName = "html/" & i.Replace("\", "/")
        '        file.FileSize = New IO.FileInfo(localPath & i).Length
        '        file.SaveWithoutAudit()

        '        Console.WriteLine("Added: " & i)
        '        With New Net.WebClient
        '            .DownloadStringAsync(New Uri("http://mikeconnellministries.com/clearcache.aspx"))
        '        End With

        '    Catch ex As Exception
        '        Console.WriteLine("Error: " & i & vbTab & ex.Message)
        '        failed.Add(i)
        '        Continue For
        '    End Try
        'Next

        'IO.File.WriteAllText("failed.txt", Framework.CUtilities.ListToString(failed, vbCrLf))

        'Exit Sub




        ''Compares the files in a dropbox folder with those already uploaded, and creates products for the missing ones

        'Console.WriteLine("Downloading existing files...")
        'Dim files As CFileList = New CFile.SelectAll

        'Dim local As String() = IO.Directory.GetFiles(My.Application.Info.DirectoryPath)
        'Console.WriteLine(files.Count.ToString("n0") & " files, checking " & local.Length.ToString("n0") & " files in current folder...")

        'For Each i As String In local
        '    If Not i.ToLower.EndsWith(".mp3") Then Continue For
        '    Dim fileName As String = IO.Path.GetFileName(i)

        '    If Contains(files, fileName) Then
        '        Console.WriteLine(fileName & " - SKIPPED")
        '        Continue For
        '    End If
        '    Console.WriteLine(fileName)

        '    Dim d As DateTime = IO.File.GetCreationTime(i).Date
        '    If d.DayOfWeek = DayOfWeek.Saturday Then
        '        d.AddDays(1)
        '    Else
        '        While d.DayOfWeek <> DayOfWeek.Sunday
        '            d = d.AddDays(-1)
        '        End While
        '    End If

        '    Console.WriteLine("Inserting Product...")
        '    Dim p As New CProduct
        '    p.ProductCreated = d
        '    p.ProductIsActive = True
        '    p.ProductIsFree = True
        '    p.ProductLanguageId = ELanguage.English
        '    p.ProductName = IO.Path.GetFileNameWithoutExtension(i).Replace("_", " ")
        '    p.ProductDescription = "Baycity Outreach Center, Hastings, NZ"
        '    p.ProductTypeId = EProductType.Sermon
        '    p.SaveWithoutAudit()
        '    If p.ProductId = Integer.MinValue Then
        '        Console.WriteLine("Failed - exitting")
        '        Console.ReadLine()
        '        Exit Sub
        '    End If

        '    Console.WriteLine("Product #" & p.ProductId & " added, Inserting File...")
        '    Dim f As New CFile
        '    f.FileName = String.Concat("Audio/Sunday services/", fileName)
        '    f.FileSize = New IO.FileInfo(i).Length
        '    f.FileProductId = p.ProductId
        '    f.SaveWithoutAudit()

        '    With New Net.WebClient
        '        .DownloadStringAsync(New Uri("http://mikeconnellministries.com/clearcache.aspx"))
        '    End With

        '    'Console.WriteLine("File #" & f.FileId & " added, hit enter to continue..")
        '    'Console.ReadLine()
        'Next
        'Console.WriteLine("Done")
        'Console.ReadLine()



    End Sub


    'Download from shane willard
    Private Sub RefreshFromRss(urlRss As String, folderPath As String, Optional matchInTitle As String = Nothing)
        Dim wc As New CWebClient(3600000)

        Dim rss As String = wc.DownloadString(urlRss)
        Dim xml As New Xml.XmlDocument()
        xml.LoadXml(rss)

        Dim channel As Xml.XmlNode = CXml.ChildNode(xml.DocumentElement, "channel")
        Dim items = CXml.ChildNodes(channel, "item")

        'Console.WriteLine(items(0).OuterXml)
        'Console.ReadLine()

        For Each i As Xml.XmlNode In items
            Dim title As String = CXml.ChildNodeGetStr(i, "title")
            If Not IsNothing(matchInTitle) Then
                If Not title.ToLower.Contains(matchInTitle.ToLower) Then Continue For
            End If

            Dim enclosure As Xml.XmlNode = CXml.ChildNode(i, "enclosure")

            Dim url As String = CXml.AttributeStr(enclosure, "url")
            Console.WriteLine(title)

            Dim fileName As String = IO.Path.GetFileName(url)
            Dim filePath As String = folderPath & fileName
            If Not IO.File.Exists(filePath) Then ' OrElse True Then
                Try
                    'wc = New CWebClient(3600000)
                    'AddHandler wc.DownloadFileCompleted, AddressOf DownloadFileCompleted
                    'wc.DownloadFileAsync(New Uri(url), filePath, filePath)
                    wc.DownloadFile(url, filePath)
                Catch ex As Exception
                    Console.WriteLine(ex.Message)
                    Try
                        wc.DownloadFile(url, filePath)
                    Catch
                        Console.WriteLine("Failed twice")
                    End Try
                End Try
            End If
            If Not IO.File.Exists(filePath & ".xml") Then
                IO.File.WriteAllText(filePath & ".xml", i.OuterXml)
            End If
        Next


    End Sub
    Private Sub DownloadFileCompleted(sender As Object, e As System.ComponentModel.AsyncCompletedEventArgs)
        Dim filePath As String = e.UserState
        Console.WriteLine("Downloaded: " & CUtilities.FileSize(filePath) & "  " & IO.Path.GetFileName(filePath))
    End Sub


    Public Function LinkUrl(p As CProduct) As String
        'Return String.Concat("~/store/decide.aspx?productId=", p.ProductId, "&name=", Encode(p.ProductName.Replace(" ", "_")))
        Return String.Concat("http://mikeconnellministries.com/", p.ProductType.Plural.Replace(" ", "_").ToLower, "/", p.ProductId, "/", System.Web.HttpUtility.UrlEncode(p.ProductName.Replace(" ", "_").Replace("&", "and")), ".aspx")
    End Function


#Region "Convert Doc files to Htm"
    Private Sub RecurseFolder_ConvertDoc2Htm(folderPath As String)
        For Each i As String In IO.Directory.GetDirectories(folderPath)
            RecurseFolder_ConvertDoc2Htm(i)
        Next

        For Each i As String In IO.Directory.GetFiles(folderPath)
            With i.ToLower
                If Not .EndsWith(".doc") AndAlso Not .EndsWith(".docx") Then Continue For
                If IO.Path.GetFileName(i).StartsWith("~") Then Continue For
            End With

            Console.WriteLine(IO.Path.GetFileName(i))

            Dim htmlFile As String = String.Concat(folderPath, "\", IO.Path.GetFileNameWithoutExtension(i), ".htm")
            'If Not IO.File.Exists(htmlFile) Then
            '    Try
            '        Dim doc As Word.Document = office.Documents.Open(i)
            '        doc.SaveAs(htmlFile, Word.WdSaveFormat.wdFormatFilteredHTML)
            '        doc.Close()
            '    Catch ex As Exception
            '        Console.WriteLine(ex.Message)
            '        Console.ReadLine()
            '        Continue For
            '    End Try
            'End If

            Try
                'IO.File.Delete(i)
            Catch
            End Try
        Next
    End Sub
#End Region

#Region "List Html Files"
    Private Function RecurseFolder_ListHtmFiles(folderPath As String) As List(Of String)
        Dim names As New List(Of String)
        RecurseFolder_ListHtmFiles(folderPath, folderPath.Length, names)
        Return names
    End Function
    Private Sub RecurseFolder_ListHtmFiles(folderPath As String, removeChars As Integer, names As List(Of String))
        For Each i As String In IO.Directory.GetDirectories(folderPath)
            RecurseFolder_ListHtmFiles(i, removeChars, names)
        Next

        For Each i As String In IO.Directory.GetFiles(folderPath)
            If Not i.ToLower.EndsWith(".htm") Then Continue For
            names.Add(i.Substring(removeChars))
        Next
    End Sub
#End Region

#Region "List Doc Files"
    Private Function RecurseFolder_ListDocFiles(folderPath As String) As List(Of String)
        Dim names As New List(Of String)
        RecurseFolder_ListDocFiles(folderPath, folderPath.Length, names)
        Return names
    End Function
    Private Sub RecurseFolder_ListDocFiles(folderPath As String, removeChars As Integer, names As List(Of String))
        For Each i As String In IO.Directory.GetDirectories(folderPath)
            RecurseFolder_ListDocFiles(i, removeChars, names)
        Next

        For Each i As String In IO.Directory.GetFiles(folderPath)
            If Not i.ToLower.EndsWith(".doc") Then Continue For
            names.Add(i.Substring(removeChars))
        Next
    End Sub
#End Region

#Region "List Doc Files"
    Private Function RecurseFolder_ListAllFiles(folderPath As String) As List(Of String)
        Dim names As New List(Of String)
        RecurseFolder_ListAllFiles(folderPath, folderPath.Length, names)
        Return names
    End Function
    Private Sub RecurseFolder_ListAllFiles(folderPath As String, removeChars As Integer, names As List(Of String))
        For Each i As String In IO.Directory.GetDirectories(folderPath)
            RecurseFolder_ListAllFiles(i, removeChars, names)
        Next

        For Each i As String In IO.Directory.GetFiles(folderPath)
            names.Add(i.Substring(removeChars))
        Next
    End Sub
#End Region

#Region "List Doc Files"
    Private Sub RecurseFolder_DeleteEmptyDirs(folderPath As String)
        For Each i As String In IO.Directory.GetDirectories(folderPath)
            RecurseFolder_DeleteEmptyDirs(i)
        Next

        If 0 = IO.Directory.GetDirectories(folderPath).Length + IO.Directory.GetFiles(folderPath).Length Then
            IO.Directory.Delete(folderPath)
            Console.WriteLine("Deleted: " & folderPath)
        End If
    End Sub
#End Region

    Private Function Contains(files As CFileList, fileName As String) As Boolean
        fileName = fileName.ToLower
        For Each j As CFile In files
            If j.FileName.ToLower().Contains(fileName) Then Return True
        Next
        Return False
    End Function

End Module
